package com.boot2.core.service;

import com.boot2.core.JpaPageRequest;
import com.boot2.core.dao.i.SysLogDao;
import com.boot2.core.dict.CommonEnum;
import com.boot2.core.model.SysLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

/**
 * @author zhangweilin
 * @ClassName: SysLogService
 * @Description: 【系统日志】 Service
 * @date 2019-9-9 14:24:47
 */
@Service
public class SysLogService {

    @Autowired
    SysLogDao sysLogDao;

    /**
     * 清除所有的无效缓存
     *
     * @param key
     */
    public void clearAllInvalidCache(String key) {
        SysLog sysLog = new SysLog();
        sysLog.setType(CommonEnum.SysLogEnum.clearAllInvalidCache.getIndex());
        sysLog.setTypeText(CommonEnum.SysLogEnum.clearAllInvalidCache.name());
        sysLog.setValue(key);
        sysLog.setDescription("清除掉死锁key: " + key);
        sysLogDao.saveAndFlush(sysLog);
    }

    /**
     * 系统重启，一般为发布版本所操作
     *
     * @param value 应用名称
     * @return
     */
    public Page<SysLog> restartApp(String value) {
        SysLog sysLog = new SysLog();
        sysLog.setType(CommonEnum.SysLogEnum.restartApp.getIndex());
        sysLog.setTypeText(CommonEnum.SysLogEnum.restartApp.name());
        sysLog.setValue(value);
        sysLog.setDescription("系统重启，一般为发布版本所操作");
        sysLogDao.saveAndFlush(sysLog);

        Page<SysLog> sysLogPage = findByTypeAndValue(CommonEnum.SysLogEnum.restartApp.getIndex(), value, 100);
        return sysLogPage;
    }

    /**
     * 分页查最后count条,倒序
     *
     * @param type
     * @return
     */
    public Page<SysLog> findByTypeAndValue(int type, String value, int count) {
        PageRequest pageRequest = JpaPageRequest.of(1, count, Sort.Direction.DESC, "id");
        Page<SysLog> sysLogPage = sysLogDao.findByTypeAndValue(type, value, pageRequest);
        return sysLogPage;
    }
}
